package com.smf.lsc.msrf.fegin.config;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

/**
 * c微服务引擎fegin配置信息，包括扫描类、拦截器等
 * c拦截fegin调用,补充header信息,便于登录信息在服务间传递
 * Created on 2021/11/19.
 *
 * @author ln
 * @since 1.0
 */
@Configuration
@EnableFeignClients(basePackages = {"com.lsc.*","${lsc.service.package:''}"})
@EnableDiscoveryClient
@ConditionalOnProperty(prefix="lsc.service",name = "type", havingValue = "fegin",matchIfMissing=true)
@Order(2)
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {
	
	@Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);
            }
            log.debug("MSRF-Fegin Debug Message: 调用前传递用户信息成功");
        }
        else
        {
        	log.debug("MSRF-Fegin Debug Message: 调用前无法获得用户信息【请检查Request Header信息】");
        }
    }
}